rm(list = ls())

wd <- ".../Replication/"
setwd(wd)

# Load/install packages --
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  foreign, 
  ggplot2, 
  estimatr,
  texreg,
  xtable,
  fastDummies,
  sandwich,
  dplyr,
  janitor, 
  gridExtra,
  gsheet,
  zoo,
  interflex,
  lubridate,
  tidyverse,
  stringi,
  readxl,
  ri2,
  modelsummary,
  ggpubr
)

options(scipen=999)

# Note: given the random component inherent to the randomization tests performed
# by ri(), you may observe small differences in the p-values of the randomization
# tests performed using that function.

# Figure 2 --------------------------------------------------------------------

lottery <- read.csv("Data/baseline database.csv")
d <- subset(lottery, lottery$group!="Liberado por eleccion")

mylabels <- c(paste0("Enslaved\n(N=", sum(d$lottery_winner==0), ")"), 
              paste0("Emancipated\n(N=", sum(d$lottery_winner==1), ")"))
interval1 <- -qnorm((1-0.90)/2)  # 90% multiplier
interval2 <- -qnorm((1-0.95)/2)  # 95% multiplier

figdata <- Rmisc::summarySE(d, 
                            measurevar="imprisoned_dummy", 
                            groupvars=c("lottery_winner"))

figdata$point <- sprintf(figdata$imprisoned_dummy*100, fmt = '%#.2f')


# ri p-values
declare <- declare_ra(N = nrow(d), m=sum(d$lottery_winner)) 
ri = summary(conduct_ri(formula = imprisoned_dummy ~ lottery_winner,
                   declaration = declare, sharp_hypothesis = 0, assignment = "lottery_winner",
                   data = d, sims = 10000))

ITT_CACE_pri_incarc <- paste0(
  "ITT: ", round(ri$estimate,3)*100,"%p\n",
  "(ri p=", round(ri$two_tailed_p_value,3),")\n","\n"
)


title <- " "
pd <- position_dodge(0.1)
imprisoned01 <- ggplot(figdata, aes(x=factor(lottery_winner), 
                                    y=100*imprisoned_dummy, 
                                    fill=factor(lottery_winner))) +
  geom_bar(stat="identity", width=0.45, alpha=0.9) +
  geom_text(aes(label = point), size = 4.0, vjust=-0.5, hjust = 0.4, nudge_x = 0) +
  ggtitle(title) +
  xlab("") +
  ylab("Imprisoned (%)") +
  ylim(-2, 26) +
  scale_x_discrete(breaks=c("0", "1"), labels=mylabels)+
  theme_minimal() +
  theme(axis.text.y=element_text(colour = "gray30", size=11), axis.ticks.y=element_blank()) +
  theme(axis.text.x=element_text(colour = "gray30", size=11), axis.ticks.x=element_line(colour="gray30")) +
  geom_segment(aes(x=1, y=21, xend=1.2, yend=23), colour="darkgray") +
  geom_segment(aes(x=1.2, y=23, xend=1.8, yend=23), colour="darkgray") +
  geom_segment(aes(x=1.8, y=23, xend=2, yend=21), colour="darkgray") + 
  annotate("text", x=1.5, y=24, label=ITT_CACE_pri_incarc, size=4) + 
  scale_fill_grey() +   
  theme_minimal() +
  theme(legend.position="none")

pdf("Output/Figure2.pdf",height=5, width=5)
imprisoned01
dev.off()
